from bs4 import BeautifulSoup

# html = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
# <p class="story">Once upon a time there were three little sisters; and their names were
# <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
# <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
# <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
# and they lived at the bottom of a well.</p>
# <p class="story">...</p>
# """

# soup = BeautifulSoup(html, 'lxml') # 在这步时对html进行更正和补全，html和body节点
# print(soup.prettify()) # 把要解析的字符串以标准的缩进格式输出
# print(soup.title.string)


# print(soup.title)
# print(type(soup.title))
# print(soup.title.string)
# print(soup.head)
# print(soup.p)
# 获取名称，先获取title节点，再调用name属性就可以得到节点名称
# print(soup.title.name)

# 获取属性
# print(soup.p.attrs)
# print(soup.p.attrs['name'])
# 简写方式
# print(soup.p['name'])
# print(soup.p['class'])
# 获取内容
# print(soup.p.string)

# 嵌套选择
# html = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# """
# soup = BeautifulSoup(html, 'lxml')
# print(soup.head.title)
# print(type(soup.head.title))
# print(soup.head.title.string)


# 关联选择
# 子节点和子孙节点
# html = """
# <html>
# <head><title>The Dormouse's story</title></head>
# <body>
#     <p class="story">
#         Once upon a time there were three little sisters; and their names were
#         <a href="http://example.com/elsie" class="sister" id="link1">
#             <span>Elsie</span>
#         </a>,
#         <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
#         <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
#         and they lived at the bottom of a well.
#     </p>
#     <p class="story">...</p>
# """
# # 获取到的是所有直接子节点
# soup = BeautifulSoup(html, 'lxml')
# # print(soup.p.contents)
#
# # 另一种方法获取直接子节点
# # print(soup.p.children)
# # for i, child in enumerate(soup.p.children):
# #     print(i, child)
#
# # 获取子孙节点，调用descendants属性
# print(soup.p.descendants)
# for i, child in enumerate(soup.p.descendants):
#     print(i, child)


# 父节点和祖先节点
# 获取父节点
html = """
<html>
<head><title>The Dormouse's story</title></head>
<body>
    <p class="story">
        Once upon a time there were three little sisters; and their names were 
        <a href="http://example.com/elsie" class="sister" id="link1">
            <span>Elsie</span>
        </a>.
    </p>
    <p class="story">...</p>
"""
soup = BeautifulSoup(html, 'lxml')
print(soup.a.parent)
print('---------------')
print(type(soup.a.parents))
print(list(enumerate(soup.a.parents)))